"""
响应包装工具
"""
import uuid
from typing import Any, Optional
from datetime import datetime
from fastapi import Request
from models.response import (
    ResponseMetadata,
    SuccessResponse,
    ErrorResponse,
    ErrorInfo,
    ErrorCode,
    ErrorMessage
)


def get_request_id(request: Request) -> str:
    """
    获取或生成 RequestId
    优先从请求头 X-Request-Id 获取，如果没有则生成新的
    """
    request_id = request.headers.get("X-Request-Id")
    if not request_id:
        request_id = str(uuid.uuid4())
    return request_id


def create_metadata(
    request: Request,
    action: str,
    service: str,
    version: str = "v1"
) -> ResponseMetadata:
    """创建响应元数据"""
    request_id = get_request_id(request)
    timestamp = datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ")
    
    return ResponseMetadata(
        RequestId=request_id,
        Action=action,
        Version=version,
        Service=service,
        Timestamp=timestamp
    )


def success_response(
    request: Request,
    action: str,
    service: str,
    result: Any = None,
    version: str = "v1"
) -> dict:
    """
    创建成功响应
    
    Args:
        request: FastAPI 请求对象
        action: 接口名称
        service: 服务模块名称
        result: 返回数据
        version: 接口版本
    
    Returns:
        dict: 标准响应格式
    """
    metadata = create_metadata(request, action, service, version)
    
    # 如果 result 为 None，返回空字符串
    if result is None:
        result = ""
    
    response = SuccessResponse(
        ResponseMetadata=metadata,
        Result=result
    )
    
    return response.model_dump(exclude_none=True)


def error_response(
    request: Request,
    action: str,
    service: str,
    code: str,
    message: Optional[str] = None,
    detail: Optional[str] = None,
    version: str = "v1"
) -> dict:
    """
    创建错误响应
    
    Args:
        request: FastAPI 请求对象
        action: 接口名称
        service: 服务模块名称
        code: 错误码
        message: 错误信息（可选，默认根据错误码获取）
        detail: 详细错误说明（可选）
        version: 接口版本
    
    Returns:
        dict: 标准错误响应格式
    """
    metadata = create_metadata(request, action, service, version)
    
    # 如果没有提供错误信息，从错误码映射中获取
    if message is None:
        message = ErrorMessage.get(code)
    
    error_info = ErrorInfo(
        Code=code,
        Message=message,
        Detail=detail
    )
    
    response = ErrorResponse(
        ResponseMetadata=metadata,
        Error=error_info
    )
    
    return response.model_dump(exclude_none=True)


# 便捷函数
def success(request: Request, action: str, service: str, result: Any = None) -> dict:
    """快捷成功响应"""
    return success_response(request, action, service, result)


def error(
    request: Request,
    action: str,
    service: str,
    code: str,
    message: Optional[str] = None,
    detail: Optional[str] = None
) -> dict:
    """快捷错误响应"""
    return error_response(request, action, service, code, message, detail)

